<?php

class Producto extends ModelBase{
  protected static $table = "productos";
  protected static $composicion_table = "productos_composicion";
  protected static $imagenes_table = "productos_imagenes";
  protected static $usuarios_table = "user";
  
  public $pages = 1;
  
  public function composicion($new_comp = null){
    if(is_null($new_comp)) {
        if(!empty($this->data['id'])){
            return $this->db()->executeOrException( 
              "SELECT * FROM ". static::$composicion_table . " WHERE producto_id = :producto_id ORDER BY orden ASC",
              array(":producto_id" => $this->data['id'])
            )->fetchAll(PDO::FETCH_ASSOC);
        } else {
          return array();  
        }
    } else {
        if(!empty($this->data['id'])){
          // borra la composicion actual
          $this->db()->executeOrException(
              "DELETE FROM ". static::$composicion_table . " WHERE producto_id = :producto_id ",
              array(":producto_id" => $this->data['id'])
            );
          // guarda la nueva
          $compo = new Composicion();
          foreach($new_comp as $c){
            $compo->data($c)->save();      
          }
          return $this;
        }
    }
  }

  public function editor(){
    $editor = array();

    if(!empty($this->data['laboratorio'])){
        $editor = $this->db()->executeOrException(
          "SELECT * FROM ". static::$usuarios_table . " WHERE lab_name = :laboratorio",
          array(":laboratorio" => $this->data['laboratorio'])
        )->fetch(PDO::FETCH_ASSOC);
    }

    return $editor;
  }
 
   public function imagenes(){
    $imagenes = array();
    
    if(isset($this->data['imagen'])) $imagenes[0] = $this->data['imagen'];
    
    if(!empty($this->data['laboratorio'])){
        $img = $this->db()->executeOrException( 
          "SELECT lab_image FROM ". static::$usuarios_table . " WHERE lab_name = :laboratorio",
          array(":laboratorio" => $this->data['laboratorio'])
        )->fetch(PDO::FETCH_ASSOC);
        
        if(!empty($img) && !empty($img['lab_image'])) $imagenes[1] = $img['lab_image'];
        
    }
     
    return $imagenes;  
    
  }
 
  
  public function paises($array_paises = null){
    if(is_null($array_paises)){
        return explode("|",trim($this->data['paises'] ,"|"));
    } else {
        $this->data['paises'] = "|".implode("|", $array_paises)."|";
        return $this;
    }
  }
  
  public function especies($array_especies = null){
    if(is_null($array_especies)){
        return explode("|",trim($this->data['especies'] ,"|"));
    } else {
        $this->data['especies'] = "|".implode("|", $array_especies)."|";
        return $this;
    }
  }
  
  public function buscar($options = array()){
    $params = isset($options['params'])?$options['params']:array();
    $page = isset($options['page'])?$options['page']:array();
    $order  = isset($options["order"])? " ORDER BY " . $options["order"] ." ": "";
    $limit  = " LIMIT " . ($page-1) * $this->per_page .", ". $this->per_page ." ";
    
    $cond = array();
    $params_query = array();
    
    if(!empty($params['especie'])) {
        $cond[] = "especies LIKE :especie";
        $params_query[":especie"] = "%|".$params['especie']."|%"; 
    }

    if(!empty($params['pais'])) {
        $cond[] = "paises LIKE :pais";
        $params_query[":pais"] = "%|".$params['pais']."|%"; 
    }
    
    if(!empty($params['ind'])) {
        $cond[] = "CONCAT(detail1, detail2, indicacion, indicacion2) LIKE _utf8 :indicacion COLLATE utf8_general_ci";
//        $cond[] = "CONCAT(detail1, detail2, indicacion, indicacion2) LIKE :indicacion";
        $params_query[":indicacion"] = "%".$params['ind']."%";
    }
    
    if(!empty($params['pactivo'])) {
        $cond[] = "principioactivo LIKE :principioactivo";
        $params_query[":principioactivo"] = "%".$params['pactivo']."%";
    }
    
    if(!empty($params['nombre'])) {
        $cond[] = "nombre LIKE :nombre";
        $params_query[":nombre"] = "%".$params['nombre']."%";
    }
    
    if(!empty($params['lab'])) {
        $cond[] = "laboratorio LIKE _utf8 :laboratorio COLLATE utf8_general_ci";
        $params_query[":laboratorio"] = "%".$params['lab']."%";
    }  
    
    if(!empty($params['status'])) {
        $cond[] = "status = :status";
        $params_query[":status"] = $params['status'];
    }  
    
    $conditions = " WHERE (".implode(") AND (", $cond).") ";
    $q = 'SELECT * FROM '.static::$table;
    $count = 'SELECT count(*) as records FROM '.static::$table;
    
    $r = $this->db()->executeOrException($count.$conditions, $params_query)->fetch(PDO::FETCH_ASSOC);
    $this->pages = ceil($r['records']/$this->per_page);
    
    $p = $this->db()->executeOrException($q.$conditions.$order.$limit, $params_query)->fetchAll(PDO::FETCH_ASSOC);
    return $p;
  }
}